import asyncio
import zmq
import zmq.asyncio


async def subscriber():
    context = zmq.asyncio.Context.instance()
    socket = context.socket(zmq.SUB)
    socket.connect("tcp://127.0.0.1:5556")  # 连接到发布端
    socket.setsockopt_string(zmq.SUBSCRIBE, "news")  # 订阅 "news" 主题

    try:
        while True:
            # 接收消息并解析
            message = await socket.recv_string()
            topic, content = message.split(" ", 1)
            print(f"Received on topic '{topic}': {content}")
    finally:
        socket.close()
        context.term()


if __name__ == "__main__":
    asyncio.run(subscriber())
